//
//  HomeworkViewController.m
//  HondaPro_2
//
//  Created by Eric on 13-7-31.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "HomeworkViewController.h"
#import "mm_jobItemGroupViewController.h"
#import "mm_userDefinedCellForResults.h"
#import "mm_userDefinedCellForIndication.h"
#import "UIViewController+MJPopupViewController.h"
#import "MJPopupBackgroundView.h"

@interface HomeworkViewController ()

@end

@implementation HomeworkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //Eric code……
    
    //初始化操作
    [self initTheHomeWorkAtFirst];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setResultTableViewDis:nil];
    [self setIndicationTableViewDis:nil];
    [self setStatementNumberTxt:nil];
    [self setStatementContentTxt:nil];
    [self setIndicationNumberTxt:nil];
    [self setIndicationContentTxt:nil];
    [self setSymptomBtn:nil];
    [self setFaultCodeBtn:nil];
    [self setActionCodeBtn:nil];
    [self setServiceTypeBtn:nil];
    [self setWorkShopBtn:nil];
    [self setRepairTypeBtn:nil];
    [super viewDidUnload];
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSInteger nRowSum = 0;
    if (tableView == self.resultTableViewDis)
    {
        nRowSum = [modelIns.arrForResults count];
    }
    else if (tableView == self.indicationTableViewDis)
    {
        if (modelIns.nRowForResults != -1)
        {
            nRowSum = [[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] count];
        }
    }
    
    return 5+nRowSum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell && tableView == self.resultTableViewDis)
    {
        cell = (mm_userDefinedCellForResults *)[[mm_userDefinedCellForResults alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    else if (nil == cell && tableView == self.indicationTableViewDis)
    {
        cell = (mm_userDefinedCellForIndication *)[[mm_userDefinedCellForIndication alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arrResultsTmp = modelIns.arrForResults;
    NSArray *arrIndicationTmp = nil;
    if (modelIns.nRowForResults != -1)
    {
        arrIndicationTmp = [[arrResultsTmp objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"];
    }
    NSMutableArray *arrResultsOrIndications = nil;
    NSArray *arrResultsOrIndicationKeys = nil;
    NSDictionary *dicResultsOrIndicationLbls = nil;
    
    /*确定要显示的列表（数组）*/
    if (tableView == self.resultTableViewDis)
    {
        arrResultsOrIndications = [NSMutableArray arrayWithArray:arrResultsTmp];
        arrResultsOrIndicationKeys = ((mm_userDefinedCellForResults *)cell).arrAllKeys;
        dicResultsOrIndicationLbls = ((mm_userDefinedCellForResults *)cell).dicAllLblsOnCell;
    }
    else if (tableView == self.indicationTableViewDis)
    {
        arrResultsOrIndications = [NSMutableArray arrayWithArray:arrIndicationTmp];
        arrResultsOrIndicationKeys = ((mm_userDefinedCellForIndication *)cell).arrAllKeys;
        dicResultsOrIndicationLbls = ((mm_userDefinedCellForIndication *)cell).dicAllLblsOnCell;
        
        //因为作业指示的列表要多显示一个陈述号，所以，给 数组 arrResultsOrIndicationKeys 每一个对象添加一个键值对：statementNumber;
        if (modelIns.nRowForResults != -1)
        {
            NSString *strStatementNumberTmp = [[arrResultsTmp objectAtIndex:modelIns.nRowForResults] objectForKey:@"statementNumber"];
            for (int i = 0; i<[arrResultsOrIndications count]; i++)
            {
                NSMutableDictionary *dicTmp = [NSMutableDictionary dictionaryWithDictionary:[arrResultsOrIndications objectAtIndex:i]];
                [dicTmp setObject:strStatementNumberTmp forKey:@"statementNumber"];
                [arrResultsOrIndications setObject:dicTmp atIndexedSubscript:i];
            }
        }
    }
    /*end of 确定要显示的列表（数组）*/
    
    /*设置 自定义Cell的数据*/
    if (row<[arrResultsOrIndications count])
    {
        for (int i = 0; i<[arrResultsOrIndicationKeys count]; i++)
        {
            NSString *strKey = [arrResultsOrIndicationKeys objectAtIndex:i];
            ((UILabel *)[dicResultsOrIndicationLbls objectForKey:strKey]).text = [[arrResultsOrIndications objectAtIndex:row] objectForKey:strKey];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        for (int i = 0; i<[arrResultsOrIndicationKeys count]; i++)
        {
            NSString *strKey = [arrResultsOrIndicationKeys objectAtIndex:i];
            ((UILabel *)[dicResultsOrIndicationLbls objectForKey:strKey]).text = @"";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    /*end of 设置 自定义Cell的数据*/
    
    return cell;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//哪几行可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSInteger nCount = 0;
    
    if (tableView == self.resultTableViewDis)
    {
        nCount = [modelIns.arrForResults count];
    }
    else if (tableView == self.indicationTableViewDis)
    {
        if (-1 != modelIns.nRowForResults)
        {
            nCount = [[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:MM_INDICATION_LIST_KEY_STR_] count];
        }
    }
    
    if ([indexPath row]<nCount)
    {
        return YES;
    }
    return NO;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if (tableView == self.resultTableViewDis)
    {
        modelIns.nRowForResults = row;
        if (row<[modelIns.arrForResults count])
        {
            [self resultsRowBeSelected];
        }
        else
        {
            [self freshenResults];
        }
    }
    else if (tableView == self.indicationTableViewDis)
    {
        modelIns.nRowForIndicationList = row;
        
        if (modelIns.nRowForResults == -1)
        {
            [self freshenIndication];
            return;
        }
        if (row<[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] count])
        {
            [self indicationRowBeSelected];
        }
        else
        {
            [self freshenIndication];
        }
    }
}

#pragma mark - 出现删除按钮时，点击按钮时的操作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"删除操作......");
    
    /*
     删除操作逻辑：
     一、
     （1）刷新用户陈述表单；
     （2）设置要删除的用户陈述和作业指示行标识；
     （3）判断选中的用户陈述，是否包含保修项目，如果包含保修项目，提示 pad不能操作保修的项目，return；
     （4）调用删除接口
     二、
     （1）刷新作业指示的表单；
     （2）设置要删除的用户陈述和作业指示行标识；
     （3）判断选中的作业指示，是否包含保修的项目，如果包含保修项目，提示 pad不能操作保修的项目，return；
     （4）调用删除接口
     */
    
    NSInteger row = [indexPath row];
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if (tableView == self.resultTableViewDis)
    {
        //（1）刷新用户陈述表单；
        [self freshenResults];
        
        //（2）设置要删除的用户陈述和作业指示行标识；
        _nStatementRowDel = row;
        _nIndicationRowDel = modelIns.nRowForIndicationList;
        
        //（3）判断选中的用户陈述，是否包含保修项目，如果包含保修项目，提示 pad不能操作保修的项目，return；
        if ([self hasWarrantyItemInStatementByStatementNumber:_nStatementRowDel andIndication:_nIndicationRowDel])
        {
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"pad不能操作保修的项目" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alerVeiw show];
            
            return;
        }
        
        //（4）调用删除接口
        NSMutableArray *arrTmp = [NSMutableArray array];
        [arrTmp addObject:@"jobSheetId"];
        [arrTmp addObject:[modelIns.dicJobSheetMsg objectForKey:@"jobSheetId"]];
        [arrTmp addObject:@"statementNumber"];
        [arrTmp addObject:[[modelIns.arrForResults objectAtIndex:row] objectForKey:@"statementNumber"]];
        [HelpClass getWebServiceDataByString:MM_CAN_DELETE_PART_ andArrObject:arrTmp];
    }
    else if (tableView == self.indicationTableViewDis)
    {
        //（1）刷新作业指示的表单；
        [self freshenIndication];
        
        //（2）设置要删除的用户陈述和作业指示行标识；
        _nStatementRowDel = modelIns.nRowForResults;
        _nIndicationRowDel = row;
        
        //（3）判断选中的作业指示，是否包含保修的项目，如果包含保修项目，提示 pad不能操作保修的项目，return；
        if ([self hasWarrantyItemInStatementByStatementNumber:_nStatementRowDel andIndication:_nIndicationRowDel])
        {
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"pad不能操作保修的项目" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alerVeiw show];
            
            return;
        }
        
        //（4）调用删除接口
        NSMutableArray *arrTmp = [NSMutableArray array];
        [arrTmp addObject:@"jobSheetId"];
        [arrTmp addObject:[modelIns.dicJobSheetMsg objectForKey:@"jobSheetId"]];
        [arrTmp addObject:@"statementNumber"];
        [arrTmp addObject:[[modelIns.arrForResults objectAtIndex:_nStatementRowDel] objectForKey:MM_RESULTS_STATE_NUMBER_KEY_STR_]];
        [arrTmp addObject:@"indicationnumber"];
        [arrTmp addObject:[[[[modelIns.arrForResults objectAtIndex:_nStatementRowDel] objectForKey:MM_INDICATION_LIST_KEY_STR_] objectAtIndex:_nIndicationRowDel] objectForKey:MM_INDICATION_INDICATION_NUMBER_KEY_STR_]];
        [HelpClass getWebServiceDataByString:MM_CAN_DELETE_PART_ andArrObject:arrTmp];
    }
}

- (IBAction)backBtnPressed:(UIButton *)sender
{
    //当要退出该界面的时候，移除所有注册过的消息
    [self removeObserverAtLast];
    
    //返回上一级界面
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)jobItemGroupBtnPressed:(UIButton *)sender
{
    //（1）判断用户陈述有没有被选中，如果没选中，提示选择用户陈述，return；否则继续；
    if ([MainMenuDataModel sharedMainMenuDataModel].nRowForResults == -1)
    {
        //提示选择用户陈述
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"未选中用户陈述！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）跳转到成组录入的界面
    mm_jobItemGroupViewController *vc = [[mm_jobItemGroupViewController alloc] initWithNibName:@"mm_jobItemGroupViewController" bundle:nil];
    vc.arrOriginalDataForServiceType = _arrOriginalDataForServiceType;
    vc.arrDisDataForServiceType = _arrDisDataForServiceType;
    
    vc.arrOriginalDataForRepairType = _arrOriginalDataForRepairType;
    vc.arrDisDataForRepairType = _arrDisDataForRepairType;
    
    vc.arrOriginalDataForWorkShop = _arrOriginalDataForWorkShop;
    vc.arrDisDataForWorkShop = _arrDisDataForWorkShop;
    
    NSLog(@"%@",vc.arrOriginalDataForServiceType);
    
    [self.navigationController pushViewController:vc animated:YES];
    
    //（4）remove 掉本类中的所有注册过的消息
    [self removeObserverAtLast];
    
    //新注册一个“成组录入”的消息
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jobItemGroupBtnPressed:) name:MM_TO_INVOKE_JOB_ITEM_GROUP_BTN_MSG_ object:nil];
}

- (IBAction)addBeginBtnPressed:(UIButton *)sender
{
    //（1）调用刷新 用户陈述 的操作
    [self freshenResults];
}

- (IBAction)indicationAddBeginBtnPressed:(UIButton *)sender
{
    //（1）如果用户陈述没有被选中，提示用户选中一个用户陈述 return；如果选择了就继续；
    if ([MainMenuDataModel sharedMainMenuDataModel].nRowForResults == -1)
    {
        //提示选择用户陈述
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"未选中用户陈述！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）调用 刷新 作业指示 的操作；
    [self freshenIndication];
}

- (IBAction)OkBtnPressed:(UIButton *)sender
{
    //（1）判断信息是否输入完整，是 继续；否则，提示信息录入不完整，return；
    if ([self.statementContentTxt.text isEqualToString:@""])
    {
        //提示录入信息不完整
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请录入用户陈述内容！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）将当前输入框中的 陈述号做判断，如果是已经存在的陈述号，那就执行修改操作；否则执行添加操作；
    if ([self.statementNumberTxt.text integerValue] <= [self resultsMaxNumber])
    {
        [self changeTheResultsDataByStatementNumber:self.statementNumberTxt.text];
    }
    else
    {
        [self addTheResultsDataByStatementNumber:self.statementNumberTxt.text];
    }
    
    //（3）调用刷新用户陈述的操作
    [self freshenResults];
    
    [self textFieldShouldReturn:self.statementContentTxt];
    [self setViewNormal];
}

- (IBAction)indicationOkBtnPressed:(UIButton *)sender
{
    /*
     （1）判断用户陈述有没有被选中，如果没选中，提示选择用户陈述，return；否则继续；
     （2）判断信息是否录入完整，如果没有录入完整，提示录入信息不完整，return；否则继续；
     （3）将指示号和当前的最大指示号比较，判断出是修改作业指示还是新增作业指示，如果是新增就调用新增作业指示方法；否则调用修改作业指示的算法；
     （4）调用刷新作业指示的方法
     */
    
    //（1）判断用户陈述有没有被选中，如果没选中，提示选择用户陈述，return；否则继续；
    if ([MainMenuDataModel sharedMainMenuDataModel].nRowForResults == -1)
    {
        //提示选择用户陈述
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"未选中用户陈述！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）判断信息是否录入完整，如果没有录入完整，提示录入信息不完整，return；否则继续；
    if (
        [self.indicationContentTxt.text isEqualToString:@""]
        ||
        -1 == _nRowServiceTypeSel
        ||
        -1 == _nRowRepairTypeSel
        ||
        -1 == _nRowWorkShop
        )
    {
        //提示选择用户陈述
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"信息录入不完整！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（3）将指示号和当前的最大指示号比较，判断出是修改作业指示还是新增作业指示，如果是新增就调用新增作业指示方法；否则调用修改作业指示的算法
    if ([self.indicationNumberTxt.text integerValue] <= [self indicationMaxNumber])
    {
        //change indication
        [self changeTheIndicationDataByStatementNumber:self.statementNumberTxt.text andIndicationNumber:self.indicationNumberTxt.text];
    }
    else
    {
        //add new indication
        [self addTheIndicationDataByStatementNumber:self.statementNumberTxt.text andIndicationNumber:self.indicationNumberTxt.text];
    }
    
    //（4）调用刷新作业指示的方法
    [self freshenIndication];
    
    [self setViewNormal];
    
    //打印
//    NSLog(@"%@",[MainMenuDataModel sharedMainMenuDataModel].arrForResults);
}

- (IBAction)codeBtnPressed:(UIButton *)sender
{
    //弹出代码选择弹出框
    _vc = [[mm_codeItemForRepairItemViewController alloc] initWithNibName:@"mm_codeItemForRepairItemViewController" bundle:nil];
    [self presentPopupViewController:_vc animationType:MJPopupViewAnimationFade];
}

- (IBAction)serviceTypeBtnPressed:(UIButton *)sender
{
    [self createThePopViewControl:sender];
    
    if (nil == _arrDisDataForServiceType)
    {
        [self getWebServiceDataByString:MM_GET_SERVICE_TYPE_LIST_ andArrObject:nil];
    }
    
    //刷新下拉菜单的数据
    _contentCon.list = _arrDisDataForServiceType;
    [_contentCon.myTableView reloadData];
}

- (IBAction)workShopBtnPressed:(UIButton *)sender
{
    [self createThePopViewControl:sender];
    
    if (nil == _arrDisDataForWorkShop)
    {
        [self getWebServiceDataByString:MM_GET_WORK_SHOP_LIST_ andArrObject:nil];
    }
        
    //刷新下拉菜单的数据
    _contentCon.list = _arrDisDataForWorkShop;
    [_contentCon.myTableView reloadData];
}

- (IBAction)repairTypeBtnPressed:(UIButton *)sender
{
    [self createThePopViewControl:sender];
    
    //刷新下拉菜单的数据
    _contentCon.list = _arrDisDataForRepairType;
    [_contentCon.myTableView reloadData];
}

//缓冲所有向服务器请求的数据
-(void)bufferingAllTheWebData
{
    [self getWebServiceDataByString:MM_GET_SERVICE_TYPE_LIST_ andArrObject:nil];
    
//    [self getWebServiceDataByString:MM_GET_REPAIR_TYPE_LIST_ andArrObject:nil];
    
    //此处的服务类型是写死的服务类行列表，服务类型单独了一个文件，写在资源目录里    
    _arrOriginalDataForRepairType = [[HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"indication_repairType" andType:@"json"] objectForKey:@"repairTypeList"];
    _arrDisDataForRepairType = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForRepairType count]];
    for (int i = 0; i<[_arrOriginalDataForRepairType count]; i++)
    {
        [_arrDisDataForRepairType addObject:[[_arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeName"]];
    }
    
    [self getWebServiceDataByString:MM_GET_WORK_SHOP_LIST_ andArrObject:nil];
}

//创建下拉菜单
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!_contentCon)
    {
        _contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    _contentCon.delegate = self;
    _contentCon.btnSender=sender;
    
    _popCon = [[UIPopoverController alloc] initWithContentViewController:_contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [_popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [_popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [_popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    if (btn == self.serviceTypeBtn)
    {
        if ([self serviceOrRepairTypeCanSelByServiceTypeId:[self getServiceTypeIdByRowSel:row] andRepairTypeId:[self getRepairTypeIdByRowSel:_nRowRepairTypeSel]])
        {
            _nRowServiceTypeSel = row;
        }
    }
    else if (btn == self.repairTypeBtn)
    {
        if ([self serviceOrRepairTypeCanSelByServiceTypeId:[self getServiceTypeIdByRowSel:_nRowServiceTypeSel] andRepairTypeId:[self getRepairTypeIdByRowSel:row]])
        {
            _nRowRepairTypeSel = row;
            
            [self repairTypeControlWorkShopTypeByRepairTypeRowSel:row];
        }
    }
    else if (btn == self.workShopBtn)
    {
        _nRowWorkShop = row;
    }
    
    /*
     serviceTypeId
     serviceTypeName
     repairTypeId
     repairTypeName
     */
    
    //设置按钮的显示
    if (-1 != _nRowServiceTypeSel)
    {
        [self.serviceTypeBtn setTitle:[[_arrOriginalDataForServiceType objectAtIndex:_nRowServiceTypeSel] objectForKey:@"serviceTypeName"] forState:UIControlStateNormal];
    }
    else
    {
        [self.serviceTypeBtn setTitle:@"" forState:UIControlStateNormal];
    }
    if (-1 != _nRowRepairTypeSel)
    {
        [self.repairTypeBtn setTitle:[[_arrOriginalDataForRepairType objectAtIndex:_nRowRepairTypeSel] objectForKey:@"repairTypeName"] forState:UIControlStateNormal];
    }
    else
    {
        [self.repairTypeBtn setTitle:@"" forState:UIControlStateNormal];
    }
    //退出弹出框
    _contentCon.list = nil;
    [_popCon dismissPopoverAnimated:YES];
    _popCon = nil;
}

//刷新作业指示的方法
-(void)freshenIndication
{
    //（1）重新装载数据，即 reload 作业指示 表单；
    [self.indicationTableViewDis reloadData];
    
    //（2）关于 作业指示 的数据（输入框、下拉菜单）全部清空（@“”），并自动设置作业指示号；
    
    //清空界面上的显示数据
    if ([self indicationSum] == 0)
    {
        self.indicationNumberTxt.text = @"1";
    }
    else
    {
        self.indicationNumberTxt.text = [NSString stringWithFormat:@"%i",[self indicationMaxNumber]+1];
    }
    self.indicationContentTxt.text = @"";
    [self.symptomBtn setTitle:@"" forState:UIControlStateNormal];
    [self.faultCodeBtn setTitle:@"" forState:UIControlStateNormal];
    [self.actionCodeBtn setTitle:@"" forState:UIControlStateNormal];
    [self.serviceTypeBtn setTitle:@"" forState:UIControlStateNormal];
    [self.workShopBtn setTitle:@"" forState:UIControlStateNormal];
    [self.repairTypeBtn setTitle:@"" forState:UIControlStateNormal];
    
    //清空数据
    [MainMenuDataModel sharedMainMenuDataModel].nRowForIndicationList = -1;
    [MainMenuDataModel sharedMainMenuDataModel].strSymptomCode = @"";
    [MainMenuDataModel sharedMainMenuDataModel].strFaultCode = @"";
    [MainMenuDataModel sharedMainMenuDataModel].strActionCode = @"";
    _nRowRepairTypeSel = -1;
    _nRowServiceTypeSel = -1;
    _nRowWorkShop = -1;
}

//刷新用户陈述的方法
-(void)freshenResults
{
    //（1）将用户陈述、作业指示的选中行标识设为默认值 －1；
    [MainMenuDataModel sharedMainMenuDataModel].nRowForResults = -1;
    [MainMenuDataModel sharedMainMenuDataModel].nRowForIndicationList = -1;
    
    if ([[MainMenuDataModel sharedMainMenuDataModel].arrForResults count])
    {
        [MainMenuDataModel sharedMainMenuDataModel].nRowForResults = 0;
    }
        
    //（2）重新装载数据，即 reload用户陈述；
    [self.resultTableViewDis reloadData];
    
    //（3）陈述号自动设置，陈述内容清空（@“”）；
    self.statementNumberTxt.text = [NSString stringWithFormat:@"%i",[self resultsMaxNumber]+1];
    self.statementContentTxt.text = @"";
    
    //（4）调用 刷新 作业指示 的操作；
    [self freshenIndication];
}

//进入界面时的初始化操作
-(void)initTheHomeWorkAtFirst
{
    //首先注册消息
    [self addObserverAtFirst];
    
    //缓冲数据
    [self bufferingAllTheWebData];
    
    //刷新用户陈述表单
    [self freshenResults];
}

//返回用户陈述的个数
-(NSInteger)resultsSum
{
    return [[MainMenuDataModel sharedMainMenuDataModel].arrForResults count];
}

//返回作业指示的总个数
-(NSInteger)indicationSum
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    if (modelIns.nRowForResults != -1)
    {
        return [[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] count];
    }
    
    return 0;
}

//得到最大陈述号的算法
-(NSInteger)resultsMaxNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSInteger nMaxTmp = 0;
    
    for (int i = 0; i<[self resultsSum]; i++)
    {
        nMaxTmp = (NSInteger)[[[modelIns.arrForResults objectAtIndex:i] objectForKey:@"statementNumber"]integerValue] > nMaxTmp ? (NSInteger)[[[modelIns.arrForResults objectAtIndex:i] objectForKey:@"statementNumber"]integerValue] : nMaxTmp;
    }
    
    return nMaxTmp;
}

//得到最大作业指示的算法
-(NSInteger)indicationMaxNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSInteger nMaxTmp = 0;
    
    NSArray *arrTmp = nil;
    
    if (modelIns.nRowForResults != -1)
    {
        arrTmp = [[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"];
    }
    
    for (int i = 0; i<[self indicationSum]; i++)
    {
        nMaxTmp = (NSInteger)[[[arrTmp objectAtIndex:i] objectForKey:@"indicationNumber"]integerValue] >nMaxTmp ? (NSInteger)[[[arrTmp objectAtIndex:i] objectForKey:@"indicationNumber"]integerValue] : nMaxTmp;
    }
    
    return nMaxTmp;
}

//用户陈述行选中的操作
-(void)resultsRowBeSelected
{
    //（1）用户陈述表单下方的 陈述号 、陈述内容 设置成和选中行的信息一致；
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    self.statementNumberTxt.text = [[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"statementNumber"];
    self.statementContentTxt.text = [[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"stateContent"];
    
    //（2）调用刷新作业指示的操作；
    [self freshenIndication];
}

//作业指示行选中的操作
-(void)indicationRowBeSelected
{
    //（1）作业指示表单下方的 信息设置成和选中行的信息一致；
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSDictionary *dicTmp = [[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList];
    
    //进行赋值
    self.indicationNumberTxt.text = [dicTmp objectForKey:@"indicationNumber"];
    self.indicationContentTxt.text = [dicTmp objectForKey:@"indicationContent"];
    
    [self.symptomBtn setTitle:[dicTmp objectForKey:@"symptomCode"] forState:UIControlStateNormal];
    [self.faultCodeBtn setTitle:[dicTmp objectForKey:@"faultCodeNumber"] forState:UIControlStateNormal];
    [self.actionCodeBtn setTitle:[dicTmp objectForKey:@"actionCode"] forState:UIControlStateNormal];
    //根据id号搜索服务类型
    for (int i = 0; i<[_arrOriginalDataForServiceType count]; i++)
    {
        NSDictionary *obj = [_arrOriginalDataForServiceType objectAtIndex:i];
        if ([[obj objectForKey:@"serviceTypeId"] isEqualToString:[dicTmp objectForKey:@"serviceType"]])
        {
            _nRowServiceTypeSel = i;
            [self.serviceTypeBtn setTitle:[obj objectForKey:@"serviceTypeName"] forState:UIControlStateNormal];
        }
    }
    //根据id号搜索修理类型
    for (int i = 0; i<[_arrOriginalDataForRepairType count]; i++)
    {
        NSDictionary *obj = [_arrOriginalDataForRepairType objectAtIndex:i];
        if ([[obj objectForKey:@"repairTypeId"] isEqualToString:[dicTmp objectForKey:@"repairTypeName"]])
        {
            _nRowRepairTypeSel = i;
            [self.repairTypeBtn setTitle:[obj objectForKey:@"repairTypeName"] forState:UIControlStateNormal];
        }
    }
    
    //根据 name 搜索车间区分
    for (int i = 0; i<[_arrOriginalDataForWorkShop count]; i++)
    {
        NSDictionary *obj = [_arrOriginalDataForWorkShop objectAtIndex:i];
        
        //如果发现字符串中有“车间”，解析json数据文件workShopList1.json，否则 解析json数据文件workShopList2.json
        if ([[dicTmp objectForKey:@"workshopName"] rangeOfString:@"车间"].length == 2)
        {
            _arrOriginalDataForWorkShop = [[HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"workShopList1" andType:@"json"] objectForKey:@"workshopList"];
            _arrDisDataForWorkShop = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForWorkShop count]];
            for (int i = 0; i<[_arrOriginalDataForWorkShop count]; i++)
            {
                [_arrDisDataForWorkShop addObject:[[_arrOriginalDataForWorkShop objectAtIndex:i] objectForKey:@"workshopName"]];
            }
        }
        else if ([[dicTmp objectForKey:@"workshopName"] rangeOfString:@"工场"].length == 2)
        {
            _arrOriginalDataForWorkShop = [[HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"workShopList2" andType:@"json"] objectForKey:@"workshopList"];
            _arrDisDataForWorkShop = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForWorkShop count]];
            for (int i = 0; i<[_arrOriginalDataForWorkShop count]; i++)
            {
                [_arrDisDataForWorkShop addObject:[[_arrOriginalDataForWorkShop objectAtIndex:i] objectForKey:@"workshopName"]];
            }
        }
        
        if ([[obj objectForKey:@"workshopName"] isEqualToString:[dicTmp objectForKey:@"workshopName"]])
        {
            _nRowWorkShop = i;
            [self.workShopBtn setTitle:[obj objectForKey:@"workshopName"] forState:UIControlStateNormal];
        }
    }
}

//修改用户陈述信息的操作
-(void)changeTheResultsDataByStatementNumber:(NSString *)statementNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
    
    //遍历用户陈述号，查找到要修改的用户陈述号，进行修改操作
    for (int i = 0; i<[modelIns.arrForResults count]; i++)
    {
        NSMutableDictionary *dicTmp = [NSMutableDictionary dictionaryWithDictionary:[modelIns.arrForResults objectAtIndex:i]];
        if ([[dicTmp objectForKey:@"statementNumber"] isEqualToString:statementNumber])
        {
            [dicTmp setObject:statementNumber forKey:@"statementNumber"];
            [dicTmp setObject:self.statementContentTxt.text forKey:@"stateContent"];
            [modelIns.arrForResults setObject:dicTmp atIndexedSubscript:i];
            
            return;
        }
    }
}

//修改作业指示信息的操作
-(void)changeTheIndicationDataByStatementNumber:(NSString *)statementNumber andIndicationNumber:(NSString *)indicationNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
    
    //取出存有该条作业指示的字典，修改字典的数据
    NSMutableDictionary *dicTmp = [NSMutableDictionary dictionaryWithDictionary:[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList]];
    [dicTmp setObject:self.indicationContentTxt.text forKey:@"indicationContent"];
    [dicTmp setObject:self.symptomBtn.titleLabel.text == nil ? @"" : self.symptomBtn.titleLabel.text forKey:@"symptomCode"];
    [dicTmp setObject:self.faultCodeBtn.titleLabel.text == nil ? @"" : self.faultCodeBtn.titleLabel.text forKey:@"faultCodeNumber"];
    [dicTmp setObject:self.actionCodeBtn.titleLabel.text == nil ? @"" : self.actionCodeBtn.titleLabel.text forKey:@"actionCode"];
    [dicTmp setObject:[[_arrOriginalDataForServiceType objectAtIndex:_nRowServiceTypeSel] objectForKey:@"serviceTypeId"] forKey:@"serviceType"];
    [dicTmp setObject:[[_arrOriginalDataForRepairType objectAtIndex:_nRowRepairTypeSel] objectForKey:@"repairTypeId"] forKey:@"repairTypeName"];
    [dicTmp setObject:[[_arrOriginalDataForWorkShop objectAtIndex:_nRowWorkShop] objectForKey:@"workshopName"] forKey:@"workshopName"];
    
    //采用 衣服原理 将修改的作业指示添加进数据模型数组中
    NSMutableArray *arrIndicationList = [NSMutableArray arrayWithArray:[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"]];
    [arrIndicationList setObject:dicTmp atIndexedSubscript:modelIns.nRowForIndicationList];
    
    NSMutableDictionary *dicResult = [NSMutableDictionary dictionaryWithDictionary:[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults]];
    [dicResult setObject:arrIndicationList forKey:@"indicationList"];
    
    [modelIns.arrForResults setObject:dicResult atIndexedSubscript:modelIns.nRowForResults];
}

//新增用户陈述
-(void)addTheResultsDataByStatementNumber:(NSString *)statementNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
    
    //将新的用户陈述添加进数据模型数组中
    NSMutableDictionary *dicTmp = [NSMutableDictionary dictionaryWithDictionary:[HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"resultsTemplate" andType:@"json"]];
    [dicTmp setObject:statementNumber forKey:@"statementNumber"];
    [dicTmp setObject:self.statementContentTxt.text forKey:@"stateContent"];
    
    [modelIns.arrForResults addObject:dicTmp];
}

//新增作业指示
-(void)addTheIndicationDataByStatementNumber:(NSString *)statementNumber andIndicationNumber:(NSString *)indicationNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
    
    //构建一个新的作业指示 字典
    NSMutableDictionary *dicIndication = [NSMutableDictionary dictionaryWithDictionary:[HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"indicationTemplate" andType:@"json"]];
    [dicIndication setObject:self.indicationNumberTxt.text forKey:@"indicationNumber"];
    [dicIndication setObject:self.indicationContentTxt.text forKey:@"indicationContent"];
    [dicIndication setObject:self.symptomBtn.titleLabel.text == nil ? @"" : self.symptomBtn.titleLabel.text forKey:@"symptomCode"];
    [dicIndication setObject:self.faultCodeBtn.titleLabel.text == nil ? @"" : self.faultCodeBtn.titleLabel.text forKey:@"faultCodeNumber"];
    [dicIndication setObject:self.actionCodeBtn.titleLabel.text == nil ? @"" : self.actionCodeBtn.titleLabel.text forKey:@"actionCode"];
    [dicIndication setObject:[[_arrOriginalDataForServiceType objectAtIndex:_nRowServiceTypeSel] objectForKey:@"serviceTypeId"] forKey:@"serviceType"];
    [dicIndication setObject:[[_arrOriginalDataForRepairType objectAtIndex:_nRowRepairTypeSel] objectForKey:@"repairTypeId"] forKey:@"repairTypeName"];
    [dicIndication setObject:[[_arrOriginalDataForWorkShop objectAtIndex:_nRowWorkShop] objectForKey:@"workshopName"] forKey:@"workshopName"];
    
    //采用 衣服原理 将新的作业指示字典添加进数据模型数组中
    NSMutableArray *arrIndicationList = [NSMutableArray arrayWithArray:[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"]];
    [arrIndicationList addObject:dicIndication];
    
    NSMutableDictionary *dicResult = [NSMutableDictionary dictionaryWithDictionary:[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults]];
    [dicResult setObject:arrIndicationList forKey:@"indicationList"];
    
    [modelIns.arrForResults setObject:dicResult atIndexedSubscript:modelIns.nRowForResults];
}

/*注册消息*/
-(void)addObserverAtFirst
{
    //注册键盘消息
    [self registerNotificationForKeyBoard];
    
    //注册网络消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getServiceTypeList:) name:MM_GET_SERVICE_TYPE_LIST_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getRepairTypeList:) name:MM_GET_REPAIR_TYPE_LIST_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getWorkShopList:) name:MM_GET_WORK_SHOP_LIST_ object:nil];
    
    //注册删除判断的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCanDeleteData:) name:MM_CAN_DELETE_PART_ object:nil];
}

/*移除消息*/
-(void)removeObserverAtLast
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*webService请求数据*/

//请求网络数据
-(void)getWebServiceDataByString:(NSString *)strMsg andArrObject:(NSMutableArray *)arrWebData
{
    webService *web=[[webService alloc] init];
    web.methodName = strMsg;
    [web commonGetSharedRequest:strMsg wsparas:arrWebData];
}

/*webService回调方法*/

//请求服务类型的回调方法
-(void)getServiceTypeList:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    _arrOriginalDataForServiceType = [theJson objectForKey:@"serviceTypeList"];
    _arrDisDataForServiceType = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForServiceType count]];
    for (int i = 0; i<[_arrOriginalDataForServiceType count]; i++)
    {
        [_arrDisDataForServiceType addObject:[[_arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeName"]];
    }
}

//请求车间区分的回调方法
-(void)getWorkShopList:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    _arrOriginalDataForWorkShop = [theJson objectForKey:@"workshopList"];
    _arrDisDataForWorkShop = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForWorkShop count]];
    for (int i = 0; i<[_arrOriginalDataForWorkShop count]; i++)
    {
        [_arrDisDataForWorkShop addObject:[[_arrOriginalDataForWorkShop objectAtIndex:i] objectForKey:@"workshopName"]];
    }
}

//请求修理类型的回调方法
-(void)getRepairTypeList:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    _arrOriginalDataForRepairType = [theJson objectForKey:@"repairTypeList"];
    _arrDisDataForRepairType = [NSMutableArray arrayWithCapacity:[_arrOriginalDataForRepairType count]];
    for (int i = 0; i<[_arrOriginalDataForRepairType count]; i++)
    {
        [_arrDisDataForRepairType addObject:[[_arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeName"]];
    }
}

//请求是否可以删除用户陈述、作业指示
-(void)getCanDeleteData:(NSNotification *)notification
{
    /*
     {
     "error_code": 0,
     "error_msg": ""，
     “result”:”0”
     }
     
     0可以删除1不可以删除2没查到数据
     */
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    
    NSString *errorCodeStr = [NSString stringWithFormat:@"%@",[theJson objectForKey:@"error_code"]];
    NSString *error_msgStr = [theJson objectForKey:@"error_msg"];
    NSString *resultStr = [theJson objectForKey:@"result"];
    
    if (![errorCodeStr isEqualToString:@"0"])
    {
        //不可以删除
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:error_msgStr delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    if ([resultStr isEqualToString:@"0"])
    {
        //可以删除，调用删除的方法
        
        /*
         删除操作：
         （1）调用删除用户陈述或者作业指示的方法
         （2）调用刷新用户陈述或者作业指示的方法
         */
        
        //（1）调用删除用户陈述或者作业指示的方法
        [self delStatementAndIndicationByStatementNumber:_nStatementRowDel andIndicationNumber:_nIndicationRowDel];
        
        //（2）调用刷新用户陈述或者作业指示的方法
        [self freshenStatementAndIndicationTableByStatementNumber:_nStatementRowDel andIndicationNumber:_nIndicationRowDel];
        
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"删除成功" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
    }
    else
    {
        //不可以删除
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"此项目客户端不可以删除" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
    }
}

//重写方法
-(void)dismissPopupViewControllerWithanimationType:(MJPopupViewAnimation)animationType
{
    [super dismissPopupViewControllerWithanimationType:animationType];
    
    //设置 代码选择 btn 的值
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    [self.symptomBtn setTitle:modelIns.strSymptomCode forState:UIControlStateNormal];
    [self.faultCodeBtn setTitle:modelIns.strFaultCode forState:UIControlStateNormal];
    [self.actionCodeBtn setTitle:modelIns.strActionCode forState:UIControlStateNormal];
};

#pragma mark - 键盘托起屏幕的代理方法

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    int offset = 350;//键盘高度350
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.frame = rect;
    }
    [UIView commitAnimations];
}

//注册键盘消息
-(void)registerNotificationForKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
}

//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
}

//判断服务类型和修理类型是否可以选择
-(BOOL)serviceOrRepairTypeCanSelByServiceTypeId:(NSString *)serviceTypeId andRepairTypeId:(NSString *)repairTypeId
{
    /*
     判断规则：
     （1）服务类型中的保修（售后保修和零部件保修）和修理类型中的首保（首保和二手车首保）不能共存
     */
    
    //(1)根据Id取name
    NSString *serviceTypeName = [self getNameByServiceId:serviceTypeId];
    NSString *repairTypeName = [self getNameByRepairId:repairTypeId];
    
    //(2)根据判断规则判定
    if ([self serviceTypeIsWarranty:serviceTypeName]
        &&
        [self repairTypeIsFirstWarranty:repairTypeName])
    {
        return NO;
    }
    return YES;
}

//根据ID取name
-(NSString *)getNameByServiceId:(NSString *)serviceId
{
    for (int i = 0; i<[_arrOriginalDataForServiceType count]; i++)
    {
        NSString *strId = [[_arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeId"];
        NSString *strName = [[_arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeName"];
        if ([serviceId isEqualToString:strId])
        {
            return strName;
        }
    }
    return @"";
}

-(NSString *)getNameByRepairId:(NSString *)RepairId
{
    for (int i = 0; i<[_arrOriginalDataForRepairType count]; i++)
    {
        NSString *strId = [[_arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeId"];
        NSString *strName = [[_arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeName"];
        if ([RepairId isEqualToString:strId])
        {
            return strName;
        }
    }
    return @"";
}

//判断服务类型是否是属于“保修”
-(BOOL)serviceTypeIsWarranty:(NSString *)serviceTypeName
{
    NSRange range = [serviceTypeName rangeOfString:@"保修"];
    if (range.length == [@"保修" length])
    {
        return YES;
    }
    return NO;
}

//判断修理类型是否是属于“首保”
-(BOOL)repairTypeIsFirstWarranty:(NSString *)repairTypeName
{
    NSRange range = [repairTypeName rangeOfString:@"首保"];
    if (range.length == [@"首保" length])
    {
        return YES;
    }
    return NO;
}

//根据列表的编号取服务类型的ID
-(NSString *)getServiceTypeIdByRowSel:(NSInteger)rowSel
{
    if (-1 == rowSel)
    {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        if (-1 == modelIns.nRowForIndicationList)
        {
            return @"";
        }
        //从作业指示取出服务类型
        return [[modelIns.arrForResults objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"serviceType"];
    }
    return [[_arrOriginalDataForServiceType objectAtIndex:rowSel] objectForKey:@"serviceTypeId"];
}

//根据列表的编号取修理类型的ID
-(NSString *)getRepairTypeIdByRowSel:(NSInteger)rowSel
{
    if (-1 == rowSel)
    {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        if (-1 == modelIns.nRowForIndicationList)
        {
            return @"";
        }
        //从作业指示取出修理类型
        return [[modelIns.arrForResults objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"repairTypeName"];
    }
    return [[_arrOriginalDataForRepairType objectAtIndex:rowSel] objectForKey:@"repairTypeId"];
}

//判断用户陈述或者作业指示中是否有保修的项目
-(BOOL)hasWarrantyItemInStatementByStatementNumber:(NSInteger)statementNumber andIndication:(NSInteger)indicationNumber
{
    /*
     判断保修的逻辑：
     （1）如果只有用户陈述选中的话，判断用户陈述中有没有保修的项目，如果有返回，return YES；
     （2）如果有作业指示选中的话，判断作业指示中有没有保修的项目，如果有，return YES；
     */
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    //（1）如果只有用户陈述选中的话，判断用户陈述中有没有保修的项目，如果有返回，return YES；
    if (-1 != statementNumber
        &&
        -1 == indicationNumber)
    {
        for (int i = 0; i<[[[modelIns.arrForResults objectAtIndex:statementNumber] objectForKey:MM_INDICATION_LIST_KEY_STR_] count]; i++)
        {
            NSDictionary *dicIndicationTmp = [[[modelIns.arrForResults objectAtIndex:statementNumber] objectForKey:MM_INDICATION_LIST_KEY_STR_] objectAtIndex:i];
            NSString *serviceTypeName = [self getNameByServiceId:[dicIndicationTmp objectForKey:@"serviceType"]];
            NSRange range = [serviceTypeName rangeOfString:@"保修"];
            
            if (2 == range.length)
            {
                return YES;
            }
        }
    }
    
    //（2）如果有作业指示选中的话，判断作业指示中有没有保修的项目，如果有，return YES；
    if (-1 != statementNumber
        &&
        -1 != indicationNumber)
    {
        NSDictionary *dicIndicationTmp = [[[modelIns.arrForResults objectAtIndex:statementNumber] objectForKey:MM_INDICATION_LIST_KEY_STR_] objectAtIndex:indicationNumber];
        NSString *serviceTypeName = [self getNameByServiceId:[dicIndicationTmp objectForKey:@"serviceType"]];
        NSRange range = [serviceTypeName rangeOfString:@"保修"];
        
        if (2 == range.length)
        {
            return YES;
        }
    }
    
    return NO;
}

//根据用户陈述和作业指示序号删除用户陈述和作业指示
-(void)delStatementAndIndicationByStatementNumber:(NSInteger)statementNumber andIndicationNumber:(NSInteger)indicationNumber
{
    /*
     //（1）如果只有用户陈述，删除用户陈述
     //（2）如果有作业指示，删除用户陈述对应的作业指示
     */
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    //（1）如果只有用户陈述，删除用户陈述
    if (-1 != statementNumber
        &&
        -1 == indicationNumber)
    {
        modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
        [modelIns.arrForResults removeObjectAtIndex:statementNumber];
    }
    
    //（2）如果有作业指示，删除用户陈述对应的作业指示
    if (-1 != statementNumber
        &&
        -1 != indicationNumber)
    {
        modelIns.arrForResults = [NSMutableArray arrayWithArray:modelIns.arrForResults];
                
        //修改后的作业指示列表
        NSMutableArray *arrIndicationListTmp = [NSMutableArray arrayWithArray:[[modelIns.arrForResults objectAtIndex:statementNumber] objectForKey:MM_INDICATION_LIST_KEY_STR_]];
        [arrIndicationListTmp removeObjectAtIndex:indicationNumber];
        
        NSMutableDictionary *dicStatementTmp = [NSMutableDictionary dictionaryWithDictionary:[modelIns.arrForResults objectAtIndex:statementNumber]];
        [dicStatementTmp setObject:arrIndicationListTmp forKey:MM_INDICATION_LIST_KEY_STR_];
        
        [modelIns.arrForResults setObject:dicStatementTmp atIndexedSubscript:statementNumber];
    }
}

//根据用户陈述和作业指示序号刷新用户陈述和作业指示表单
-(void)freshenStatementAndIndicationTableByStatementNumber:(NSInteger)statementNumber andIndicationNumber:(NSInteger)indicationNumber
{    
    //（1）如果只有用户陈述，刷新用户陈述
    if (-1 != statementNumber
        &&
        -1 == indicationNumber)
    {
        [self freshenResults];
    }
    
    //（2）如果有作业指示，刷新用户陈述对应的作业指示
    if (-1 != statementNumber
        &&
        -1 != indicationNumber)
    {
        [self freshenIndication];
    }
}

//修理类型和车间区分之间的联动关系
-(void)repairTypeControlWorkShopTypeByRepairTypeRowSel:(NSInteger)repairTypeRowSel
{
    /*
     （1）修理类型选钣金，车间区分默认选中钣金车间
     （2）修理类型选喷漆，车间区分默认选中喷漆车间
     （3）修理类型选中其他类型，车间区分默认为修理车间
     */
    
    /*
     serviceTypeId
     serviceTypeName
     repairTypeId
     repairTypeName
     
     workshopName
     */
    
    NSString *strIdKey = @"repairTypeId";
    NSString *strNameKey = @"repairTypeName";
    NSString *strWorkShopNameKey = @"workshopName";
    
    NSString *repairTypeNameStrTmp = [HelpClass getNameByIndexInList:_arrOriginalDataForRepairType withIndex:repairTypeRowSel byNameKey:strNameKey byIdKey:strIdKey];
    
    if ([repairTypeNameStrTmp rangeOfString:@"钣金"].length == 2)
    {
        //修理类型选中钣金
        NSInteger nRowWorkShopTmp = [HelpClass getIndexInList:_arrOriginalDataForWorkShop withName:@"钣金" byNameKey:strWorkShopNameKey];
        NSString *strWorkShopNameSelTmp = [HelpClass getNameByIndexInList:_arrOriginalDataForWorkShop withIndex:nRowWorkShopTmp byNameKey:strWorkShopNameKey byIdKey:nil];
        [self selectDelegate:nRowWorkShopTmp btn:self.workShopBtn];
        [self.workShopBtn setTitle:strWorkShopNameSelTmp forState:UIControlStateNormal];
    }
    else if ([repairTypeNameStrTmp rangeOfString:@"喷漆"].length == 2)
    {
        //修理类型选中喷漆
        NSInteger nRowWorkShopTmp = [HelpClass getIndexInList:_arrOriginalDataForWorkShop withName:@"喷漆" byNameKey:strWorkShopNameKey];
        NSString *strWorkShopNameSelTmp = [HelpClass getNameByIndexInList:_arrOriginalDataForWorkShop withIndex:nRowWorkShopTmp byNameKey:strWorkShopNameKey byIdKey:nil];
        [self selectDelegate:nRowWorkShopTmp btn:self.workShopBtn];
        [self.workShopBtn setTitle:strWorkShopNameSelTmp forState:UIControlStateNormal];
    }
    else
    {
        //选中其它类型
        NSInteger nRowWorkShopTmp = [HelpClass getIndexInList:_arrOriginalDataForWorkShop withName:@"修理" byNameKey:strWorkShopNameKey];
        NSString *strWorkShopNameSelTmp = [HelpClass getNameByIndexInList:_arrOriginalDataForWorkShop withIndex:nRowWorkShopTmp byNameKey:strWorkShopNameKey byIdKey:nil];
        [self selectDelegate:nRowWorkShopTmp btn:self.workShopBtn];
        [self.workShopBtn setTitle:strWorkShopNameSelTmp forState:UIControlStateNormal];
    }
}

@end
